package com.zhao.fishingguideserver.interceptors;

import com.zhao.fishingguideserver.utils.JwtUtil;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;

/**
 * 管理员登录拦截器
 */
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头的Authorization（格式：Bearer Token字符串）
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"未登录或登录已过期\"}");
            return false;
        }

        // 2. 截取Token（去掉"Bearer "前缀）
        String token = authHeader.substring(7);
        try {
            // 3. 解析Token，获取claims
            Map<String, Object> claims = JwtUtil.parseToken(token);
            
            // 4. 验证是否为管理员Token（检查是否包含adminId）
            if (claims.get("adminId") == null) {
                response.setStatus(403);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":403,\"msg\":\"无管理员权限\"}");
                return false;
            }
            
            // 5. 存入ThreadLocal，供Controller获取管理员信息
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            // Token无效/过期：返回401
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"Token无效或已过期\"}");
            return false;
        }
    }

    // 拦截器完成后清除ThreadLocal，防止内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}

